use std::net::SocketAddr;

use edge_gateway::protocols::modbus::connection_pool::SlaveKey;
use edge_gateway::{config::load_config, protocols::modbus::connection_pool::ModbusConnectionPool};
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // 日志环境初始化
    env_logger::init();
    let cfg = load_config("../config/config.yml")?;
    log::info!("🚀 Starting Edge Gateway [{}]", cfg.gateway.id);


    let pool = ModbusConnectionPool::new(); loop {
        for slave in &cfg.modbus.slaves {
            let pool = pool.clone();
            let s = slave.clone();

            let name = slave.name.clone();
            let key = SlaveKey::new(slave.addr.parse::<SocketAddr>()?, slave.unit_id);

            tokio::spawn(async move {
                match pool.read_input(key.clone(), s.start_reg, s.reg_count).await {
                    Ok(data) => log::info!(
                        "[{}] data {:?} ({} regs from {})",
                        name, data, s.reg_count, s.start_reg
                    ),
                    Err(e) => log::error!("[{}] read error: {:?}", name, e),
                }
            });
        }

        sleep(Duration::from_millis(cfg.gateway.poll_interval_ms)).await;
    }
}